import Banner from '../Banner/index';
import Mode from '../Mode/index';
import Action from '../Action/index';
import { Dialog } from 'react-vant';
import './home.less';
import { useEffect, useState, useRef } from 'react';
import { deviceId } from '../../utils/staticData';
import {
  btnFitersText,
  runningTextConvert,
  workTimeMode
} from '../../utils/filters';
import { useLocation } from 'react-router-dom';
const Hejia = (window as any).Hejia;

export default function Home() {
  // 定时器变量
  const intervalId = useRef<NodeJS.Timeout | null>(null);

  const location = useLocation();

  useEffect(() => {
    setTimeout(() => {
      (window as any).bridge.callHandler(
        'setToolbarTitle',
        '海尔智能电饭煲',
        null
      );
    }, 0);
  }, [location]);

  interface IState {
    Switch: number; // 开关：0-待机 1-启动
    mode: number; // 模式: 1-保温 2-快煮饭 3-精煮饭 4-煮粥 5-煲汤 6-卤煮 7-热饭
    reserve: number; // 预约 0-1440 step=10
    Workinghours: number; // 工作时间 0-1440 step=1
    Workingcondition: number; // 工作状态 0-待机 1-工作中 2-预约中 3-保温中
    breakdown: number; // 故障 0-正常  1-5 故障
    isOnline: boolean; // false=离线 true=在线
  }
  const [deviceInfo, setDeviceInfo] = useState<IState>({
    Switch: 0,
    mode: 0,
    reserve: 0,
    Workingcondition: 0,
    Workinghours: 0,
    breakdown: 0,
    isOnline: true
  });

  useEffect(() => {
    // 这里是副作用的逻辑，类似于 componentDidMount
    intervalId.current = setInterval(() => {
      // 在这里执行你想要的操作
      getDeviceInfo();
    }, 1000);
    return () => {
      // 这里是清理副作用的逻辑，类似于 componentWillUnmount
      // 在组件卸载时清除定时器
      if (intervalId.current) {
        clearInterval(intervalId.current); // 清除定时器
      }
    };
  }, []); // 依赖数组为空，只在组件挂载和卸载时执行一次

  useEffect(() => {
    Hejia.ready(function () {
      // 页面加载完成后要立即调用Hejia全局对象执行的代码逻辑写这里
      getDeviceInfo();
    });
  }, []);

  // 解析获取到的设备信息数据
  const parseData = (params: any) => {
    params.forEach((e: any) => {
      const keys = [
        'Switch',
        'mode',
        'reserve',
        'Workinghours',
        'Workingcondition',
        'breakdown'
      ];

      if (keys.includes(e.name)) {
        setDeviceInfo(pre => ({
          ...pre, // 使用对象展开符复制原对象的属性
          [e.name]: Number(e.value) // 更新特定属性的值
        }));
      }
    });
  };
  /**
   * 轮询事件
   */
  const getDeviceInfo = () => {
    // deviceId
    Hejia.getDeviceInfo(
      {},
      function (obj: any) {
        console.log(obj, '快照接口设备参数---');
        // if (obj.device == undefined) return;

        /**
         * 第一级别：离线，设备离线级别最高，如果设备是离线状态，需要展示离线页面
         * 第二级别：故障
         */
        // 设备是否在线, 设置离线状态
        setDeviceInfo(pre => ({
          ...pre, // 使用对象展开符复制原对象的属性
          isOnline: obj.device.connected // 更新特定属性的值
        }));

        parseData(obj.device.parameters);
      },
      function (msg: any, obj: any) {
        console.log(msg, '设备参数报错了---');
        console.log(obj);
      }
    );
  };

  const handleModeChange = (val: number) => {
    console.log('handleModeChange:', val);
    setDeviceInfo(pre => ({
      ...pre, // 使用对象展开符复制原对象的属性
      mode: val,
      Workinghours: workTimeMode(val)
    }));
    if (val === 1) {
      setDeviceInfo(pre => ({
        ...pre, // 使用对象展开符复制原对象的属性
        Workingcondition: 3 // 更新特定属性的值
      }));
    }

  };

  const handleActionChange = (val: number, key: string) => {
    if (key === 'appointment') {
      setDeviceInfo(pre => ({
        ...pre,
        reserve: val
      }));
    } else if (key === 'timer') {
      setDeviceInfo(pre => ({
        ...pre,
        Workinghours: val
      }));
    }
  };

  /**
   * @description 停止/开启轮询
   * @param val {boolean} true=>开启 false=>关闭
   */
  const handleLoopClick = (val: boolean) => {
    // true=>开启 false=>关闭
    if (val) {
      if (intervalId.current) {
        clearInterval(intervalId.current);
      }
      intervalId.current = setInterval(() => {
        // 在这里执行你想要的操作
        getDeviceInfo();
      }, 1000);
    } else {
      if (intervalId.current) {
        clearInterval(intervalId.current);
      }
    }
  };

  const onCooker = () => {
    handleLoopClick(false);
    if ([1, 2, 3, 4].includes(deviceInfo.Workingcondition)) {
      let msg = `设备${runningTextConvert(
        deviceInfo.Workingcondition
      )}中，确定要取消${runningTextConvert(deviceInfo.Workingcondition)}吗？`;
      if (deviceInfo.Workingcondition === 1) {
        msg = `设备${runningTextConvert(
          deviceInfo.Workingcondition
        )}中，确定要取消运行吗？`;
      }
      Dialog.confirm({
        message: msg,
        confirmButtonText: '确定',
        confirmButtonColor: 'var(--primary-color)',
        onCancel: () => {
          handleLoopClick(true);
        },
        onConfirm: () => {
          setDeviceInfo(pre => ({
            ...pre,
            Workingcondition: 0
          }));
          // 取消烹饪
          Hejia.setControlParam(
            {
              // deviceId,
              parameters: {
                param: [
                  {
                    name: 'Switch',
                    content: 0
                  }
                ]
              }
            },
            function () {
              // success, no response
              setTimeout(() => {
                handleLoopClick(true);
              }, 2000);
              console.log('success');
            },
            function (msg: string, obj: any) {
              console.log(msg + obj);
            }
          );
        }
      });
    } else {
      // 开始运行
      if (deviceInfo.reserve > 0) {
        setDeviceInfo(pre => ({
          ...pre,
          Workingcondition: 2
        }));
      } else {
        setDeviceInfo(pre => ({
          ...pre,
          Workingcondition: 1
        }));
      }

      Hejia.setControlParam(
        {
          // deviceId,
          parameters: {
            param: [
              {
                name: 'Switch',
                content: 1
              }
            ]
          }
        },
        function () {
          // success, no response
          setTimeout(() => {
            handleLoopClick(true);
          }, 2000);
          console.log('success');
        },
        function (msg: string, obj: any) {
          console.log(msg + obj);
        }
      );
    }
  };

  return (
    <div className="home">
      <div>
        <Banner
          propsBanner={{
            status: deviceInfo.Workingcondition,
            mode: deviceInfo.mode,
            fault: deviceInfo.breakdown,
            Workinghours: deviceInfo.Workinghours,
            isOnline: deviceInfo.isOnline
          }}
        />

        {/* 模式选择 */}
        <Mode
          props={{
            mode: deviceInfo.mode,
            appointment: deviceInfo.reserve,
            status: deviceInfo.Workingcondition,
            fault: deviceInfo.breakdown,
            isOnline: deviceInfo.isOnline
          }}
          onLoopClick={handleLoopClick}
          onModeChange={handleModeChange}
        />
        {/* 工作时长，预约 */}
        <Action
          onActionChange={handleActionChange}
          onLoopClick={handleLoopClick}
          propsAction={{
            mode: deviceInfo.mode,
            fault: deviceInfo.breakdown,
            status: deviceInfo.Workingcondition,
            Workinghours: deviceInfo.Workinghours,
            appointment: deviceInfo.reserve,
            isOnline: deviceInfo.isOnline
          }}
        />

        <div className="home-mask-wapper">
          {(!deviceInfo.isOnline ||
            deviceInfo.mode === 0 ||
            !!deviceInfo.breakdown) && <div className="mask"></div>}
          <div className="footer">
            <div className="stop-btn" onClick={onCooker}>
              {btnFitersText(deviceInfo.Workingcondition, deviceInfo.reserve)}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
